package com.darren.archive.websocket;


import com.alibaba.fastjson.JSON;
import com.darren.archive.bean.ResponseBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/ws/message/{client}")
@Component
@Slf4j
public class MessageNotificationWebSocket {

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    //新：使用map对象，便于根据userId来获取对应的WebSocket
    private static ConcurrentHashMap<String, MessageNotificationWebSocket> websocketList = new ConcurrentHashMap<>();

    //客户端id
    public String client = "";

    /**
     * 连接建立成功调用的方法
     *
     * @param session  客户端的连接会话
     * @param client 客户端id
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("client") String client) {
        this.session = session;
        if (websocketList.get(this.client) != null) {
            websocketList.remove(this.client);
        }else{
            addOnlineCount();           //在线数加1
        }
        websocketList.put(client, this);
        log.info("websocketList->" + JSON.toJSONString(websocketList));
        log.info("有新窗口开始监听:" + client + ",当前在线人数为" + getOnlineCount());
        this.client = client;
        try {
            sendMessage(JSON.toJSONString(ResponseBean.isOk("连接成功")));
        } catch (IOException e) {
            log.error("websocket IO 异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if (websocketList.get(this.client) != null) {
            websocketList.remove(this.client);
            subOnlineCount();           //在线数减1
            log.info("有一连接关闭！当前在线人数为" + getOnlineCount());
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     * @param session 客户端的连接会话
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自窗口" + client + "的信息:" + message);
    }


    /**
     * @param session 客户端的连接会话
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * 群发自定义消息
     */
    public static void sendAllInfo(String message) throws IOException {
        for (Map.Entry<String, MessageNotificationWebSocket> entry : websocketList.entrySet()) {
            try {
                MessageNotificationWebSocket messageNotificationWebSocket = entry.getValue();
                if (messageNotificationWebSocket.session != null && messageNotificationWebSocket.session.isOpen()) {
                    messageNotificationWebSocket.sendMessage(message);
                }
            } catch (IOException e) {
                continue;
            }
        }
    }


    public static synchronized int getOnlineCount() {
        return MessageNotificationWebSocket.onlineCount;
    }

    public static synchronized void addOnlineCount() {
        MessageNotificationWebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        MessageNotificationWebSocket.onlineCount--;
    }

}
